package com.changgou.canal;

import com.alibaba.fastjson.JSON;
import com.alibaba.otter.canal.protocol.CanalEntry;

import com.changgou.content.feign.ContentFeign;
import com.changgou.content.pojo.Content;
import com.xpand.starter.canal.annotation.*;
import entity.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import sun.rmi.runtime.Log;

import java.util.List;

/**
 * 实现mysql 数据监听
 */
@Slf4j
@CanalEventListener
public class CanalDataEventListener {
    @Autowired
    private ContentFeign contentFeign;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    /**
     * @param eventType 当前操作的类型 增加类型
     * @param rowData   发生变更的一行数据
     */
    @InsertListenPoint
    public void onEventInsert(CanalEntry.EventType eventType, CanalEntry.RowData rowData) {
        /*增加之后每一列的数据*/
        for (CanalEntry.Column column : rowData.getAfterColumnsList()) {
            log.info("变更的列名为{}，==========》{}", column.getName(), column.getValue());
        }

    }


    @ListenPoint(eventType = {CanalEntry.EventType.DELETE, CanalEntry.EventType.INSERT, CanalEntry.EventType.UPDATE}
            , table = {"tb_content"}, // 指定表
            schema = {"changgou_content"},  // 指定数据库
            destination = "example"  // 指定实例地址
    )

    public void onEventCustomUpdate(CanalEntry.EventType eventType, CanalEntry.RowData rowData) {
        String categoryId = getColumnValue(eventType, rowData);
        Result<List<Content>> byCategory = contentFeign.findByCategory(Long.valueOf(categoryId));
        List<Content> data = byCategory.getData();//List
        stringRedisTemplate.boundValueOps("content_" + categoryId).set(JSON.toJSONString(data));

    }

    private String getColumnValue(CanalEntry.EventType eventType, CanalEntry.RowData rowData) {

        /*如果是删除，那么就要获取before的数据*/
        String categoryId = "";
        if (CanalEntry.EventType.DELETE == eventType) {
            List<CanalEntry.Column> beforeColumnsList = rowData.getBeforeColumnsList();
            for (CanalEntry.Column column : beforeColumnsList) {
                if (column.getName().equals("category_id" )) {
                    categoryId = column.getValue();
                    return categoryId;
                }
            }

        } else {
            /*如果是新增 更新 获取after的数据*/
            List<CanalEntry.Column> beforeColumnsList = rowData.getAfterColumnsList();
            for (CanalEntry.Column column : beforeColumnsList) {
                if (column.getName().equals("category_id" )) {
                    categoryId = column.getValue();
                    return categoryId;
                }
            }
        }
        return categoryId;
    }


}



